import React, { ComponentType } from 'react';
import { Button, Result } from 'antd';
import { IUser } from '@src/types/account';

interface AuthorizedProps {
  children: ComponentType<any>;
  userInfo: IUser;
  NoMatch?: React.FC<any>;
  showNoAuth?: boolean; // 是否展示没权限时的组件，不展示就是隐藏
}

// 这里不用useHistory是因在notification里面使用的时候没被包裹在Router组件中
export const NoAuth: any = () => {
  // 跳转登录
  const goToLogin = () => {
    location.pathname = '/login';
  };

  return (
    <Result
      status='403'
      title='403'
      subTitle='暂无权限访问此页面，登录后享用全部功能'
      extra={
        <Button type='primary' onClick={goToLogin}>
          立即登录
        </Button>
      }
    />
  );
};

// 校验是否登录组件
const Authorized: React.FC<AuthorizedProps> = ({
  children,
  userInfo,
  NoMatch = NoAuth,
  showNoAuth = true,
}) => <>{userInfo.uid ? children ?? null : showNoAuth ? <NoMatch /> : null}</>;

export default Authorized;
